<template>
  <div class="liveSet">
    <div class="form-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/activityPrizeList' }"
          >奖品列表</el-breadcrumb-item
        >
        <el-breadcrumb-item>核销码列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="table-bar">
      <div>
        <el-button type="primary" size="medium" @click="handleAdd"
          >生成核销码</el-button
        >
        <el-button type="primary" size="medium" @click="outFile"
          >导出</el-button
        >
      </div>
      <div class="inputSearch">
        <span style="flex-shrink: 0">发放渠道：</span>
        <el-select
          style="flex-shrink: 0; margin: 0 20px 0 0px"
          clearable
          @change="selectChannel"
          v-model="channelValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in channelType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <span style="flex-shrink: 0">获得渠道：</span>
        <el-select
          style="flex-shrink: 0; margin: 0 20px 0 0px"
          clearable
          @change="selectChannelGet"
          v-model="channelValueGet"
          placeholder="请选择"
        >
          <el-option
            v-for="item in channelTypeGet"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <span style="flex-shrink: 0">领取状态：</span>
        <el-select
          style="flex-shrink: 0; margin: 0 20px 0 0px"
          clearable
          @change="selectReceiver"
          v-model="receiverValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in receiveStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <span style="flex-shrink: 0">核销状态：</span>
        <el-select
          style="flex-shrink: 0; margin: 0 20px 0 0px"
          clearable
          @change="selectChannelUse"
          v-model="channelUseValue"
          placeholder="请选择"
        >
          <el-option
            v-for="item in channelUse"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="success" @click="backFn">返回</el-button>
      </div>
    </div>
    <div class="table-bar">
      <!-- <div style="display:flex;align-items:center;"> -->
      <h3>
        所属奖品（id）：{{ name }}（{{ id }}） <el-tag>{{ marketName }}</el-tag>
      </h3>
      <!-- </div> -->
      <div class="inputSearch">
        <el-input
          placeholder="输入领取用户信息搜索"
          v-model="receive_user"
          clearable
          @input="clearInput1"
          @keyup.enter.native="searchInput"
        ></el-input>
        <el-input
          placeholder="输入核销用户信息搜索"
          v-model="verify_user"
          clearable
          @input="clearInput2"
          @keyup.enter.native="searchInput"
        ></el-input>
        <el-input
          placeholder="输入核销码搜索"
          v-model="keyword"
          clearable
          @input="clearInput"
          @keyup.enter.native="searchInput"
        ></el-input>
        <el-button type="primary" size="medium" @click="searchInput"
          >搜索</el-button
        >
      </div>
    </div>
    <div class="partnerList_table">
      <div class="partnerList_bottom_table">
        <table>
          <tr>
            <th></th>
            <th>奖品核销码</th>
            <th>发放渠道</th>
            <th>领取用户</th>
            <th>领取用户ID</th>
            <th>获得渠道</th>
            <th>核销用户</th>
            <th>核销用户ID</th>
            <th>核销商家（ID）</th>
            <th>核销商家logo</th>
            <th>领取状态</th>
            <th>核销状态</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
          <tr v-for="(v, i) in tableList" :key="i">
            <td>
              <font
                class="checkbox"
                :class="{ check_active: checkBoxAll.includes(i) }"
                @click="handlerCheckbox(i)"
                ><i class="el-icon-check"></i
              ></font>
            </td>
            <td>{{ v.code }}</td>
            <td>{{ v.channel == 0 ? "线下" : "线上" }}</td>
            <td>
              {{ v.rec_nickname }}
              <p>{{ v.rec_mobile }}</p>
            </td>
            <td>{{ v.rec_user_id ? v.rec_user_id : "" }}</td>
            <td>
              <span v-if="v.rec_user_id > 0">{{
                v.receive_channel == 0
                  ? "抽奖"
                  : v.receive_channel == 1
                  ? "购买礼包"
                  : v.receive_channel == 2
                  ? "商城下单"
                  : ""
              }}</span>
            </td>
            <td>
              {{ v.ver_nickname }}
              <p>{{ v.ver_mobile }}</p>
            </td>
            <td>{{ v.verify_id ? v.verify_id : "" }}</td>
            <td>
              {{ v.store_name }}
              <span v-if="v.store_id">（{{ v.store_id }}）</span>
            </td>
            <td>
              <el-image
                v-if="v.store_logo"
                style="width: 60px; height: 60px"
                :src="v.store_logo"
                :preview-src-list="[v.store_logo]"
              >
              </el-image>
            </td>
            <td>{{ v.rec_user_id > 0 ? "已领取" : "未领取" }}</td>
            <td>{{ v.verify_id > 0 ? "已核销" : "未核销" }}</td>
            <td>
              <p v-if="v.created_at">生成时间：{{ v.created_at }}</p>
              <p v-if="v.receive_at">
                领取时间：{{
                  $moment(v.receive_at * 1000).format("yyyy-MM-DD HH:mm:ss")
                }}
              </p>
              <p v-if="v.verify_at">
                核销时间：{{
                  $moment(v.verify_at * 1000).format("yyyy-MM-DD HH:mm:ss")
                }}
              </p>
            </td>
            <td>
              <!-- <button class="editor" :class="{'delete':v.status==1}" @click="toChange(v.item_id,v.status)">{{v.status==1?'关闭':'开启'}}</button> -->
              <button class="yellow" @click="toDel(v.id)">删除</button>
              <!-- <button class="shelves" @click="toEdit(v.id)">编辑</button> -->
            </td>
          </tr>
          <tr v-if="tableList.length == 0">
            <td class="table_title" colspan="20">当前数据空空如也</td>
          </tr>
        </table>
        <div class="partnerList_bottom_page">
          <div class="partnerList_bottom_page_left">
            <div
              class="partnerList_bottom_page_left_checkAll"
              @click="handerCheckAll"
            >
              <font class="checkbox" :class="{ check_active: checkAll }"
                ><i class="el-icon-check"></i
              ></font>
            </div>
            全选
            <!-- <button class="partnerList_bottom_page_left_btn" @click="selectDel">删除</button> -->
          </div>
          <div class="partnerList_bottom_page_right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="生成核销码"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      @closed="closedFn"
    >
      <div>
        <span>注：0表示不是生成</span>
        <div style="margin-top: 20px">
          线下核销码份数：<el-input
            style="width: 50%"
            v-model="offline_num"
            @blur="changeOffline"
          ></el-input>
        </div>
        <div style="margin-top: 20px">
          线上核销码份数：<el-input
            style="width: 50%"
            v-model="online_num"
            @blur="changeOnline"
          ></el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="creatBtn" @click="dialogVisible = false">取 消</el-button>
        <!-- <el-button type="primary">确 定</el-button> -->
        <el-button :disabled="creatBtn" type="primary" @click="addWriteOff" :loading="creatLoad">{{creatText}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      checkAll: false,
      page: 1,
      pageSize: 10,
      total: 0,
      checkBoxAll: [], // 选中的数据
      shelvesAlls: [],
      tableList: [],
      keyword: "",
      code: "",
      activity_id: "", //主活动id
      fatherName: "", //主活动名称
      channelType: [
        {
          label: "线上",
          value: 1,
        },
        {
          label: "线下",
          value: 0,
        },
      ],
      channelValue: "", //选择的发放渠道

      channelTypeGet: [
        {
          //获得渠道
          label: "抽奖",
          value: 0,
        },
        {
          label: "购买礼包",
          value: 1,
        },
        {
          label: "商城下单",
          value: 2,
        },
      ],
      channelValueGet: "", //选择的获得渠道

      receiveStatus: [
        {
          //领取状态
          label: "未领取",
          value: 0,
        },
        {
          label: "已领取",
          value: 1,
        },
      ],
      receiverValue: "", //选择的领取状态

      channelUse: [
        {
          //核销状态
          label: "未核销",
          value: 0,
        },
        {
          label: "已核销",
          value: 1,
        },
      ],
      channelUseValue: "", //选择的核销状态

      dialogVisible: false,

      offline_num: "",
      online_num: "",
      id: "", //奖品id
      name: "", //奖品名称
      creatLoad:false,//生成核销码loading
      creatText:'确定',//生成核销码按钮文字
      creatBtn:false,//生成核销码按钮禁用

      receive_user: "", //领取用户信息
      verify_user: "", //核销用户信息
      marketId: "", //卖场id（列表筛选）
      marketName: "", //卖场名称
    };
  },
  mounted() {
    this.marketId = this.$route.query.market_id;
    this.marketName = this.$route.query.market_name;
    this.id = this.$route.query.id;
    this.name = this.$route.query.name;
    this.getSetList();
    this.remoteMethod();
  },
  methods: {
    // 获取卖场列表
    remoteMethod() {
      this.$http.post("/api/root/Market/marketList").then((res) => {
        console.log(res, "卖场列表");
        if (res.code == 1) {
          this.marketList = res.data ? res.data : [];
        }
      });
    },
    // 选择卖场
    selectMarket() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    // 获取核销码列表o
    getSetList() {
      let params = {
        prize_id: this.id,
        code: this.keyword,
        page: this.page,
        pagesize: this.pageSize,
        channel: this.channelValue,
        receive_channel: this.channelValueGet,
        receive_status: this.receiverValue,
        verify_status: this.channelUseValue,
        receive_user: this.receive_user,
        verify_user: this.verify_user,
        market_id: this.marketId,
      };
      this.$http
        .post("/api/root/activity/prizecode/lists", params)
        .then((res) => {
          console.log(res, "核销码列表");
          if (res.code == 1) {
            this.tableList = res.data.data ? res.data.data : [];
            this.total = res.data.count;

            // 每次请求清空选中
            this.checkAll = false;
            this.checkBoxAll = [];
            this.shelvesAlls = [];
          }
        });
    },

    // 返回按钮
    backFn() {
      this.$router.back(1);
    },

    // 节目列表
    toParty(id) {
      this.$router.push({ name: "partyList", query: { id } });
    },

    // 搜索
    searchInput() {
      this.page = 1;
      this.pageSize = 10;
      if (
        this.keyword != "" ||
        this.receive_user != "" ||
        this.verify_user != ""
      ) {
        this.getSetList();
      }
    },
    // 清空输入框
    clearInput() {
      this.page = 1;
      this.pageSize = 10;
      if (this.keyword == "") {
        this.getSetList();
      }
    },
    clearInput1() {
      this.page = 1;
      this.pageSize = 10;
      if (this.receive_user == "") {
        this.getSetList();
      }
    },
    clearInput2() {
      this.page = 1;
      this.pageSize = 10;
      if (this.verify_user == "") {
        this.getSetList();
      }
    },

    // 选择发放渠道
    selectChannel() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    // 选择获得渠道
    selectChannelGet() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    // 选择领取渠道
    selectReceiver() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },
    // 选择使用渠道
    selectChannelUse() {
      this.page = 1;
      this.pageSize = 10;
      this.getSetList();
    },

    // 导出按钮
    outFile() {
      // let codeKeyword = this.keyword?this.keyword:this.shelvesAlls.join(',');
      var a = document.createElement("a");
      a.setAttribute(
        "href",
        `/api/root/activity/prizecode/export?prize_id=${this.id}&prize_code=${this.keyword}&channel=${this.channelValue}&receive_channel=${this.channelValueGet}&receive_status=${this.receiverValue}&verify_status=${this.channelUseValue}&receive_user=${this.receive_user}&verify_user=${this.verify_user}`
      );
      a.setAttribute("target", "_blank");
      a.setAttribute("id", "startTelMedicine"); // 防止反复添加
      if (document.getElementById("startTelMedicine")) {
        document.body.removeChild(document.getElementById("startTelMedicine"));
      }
      document.body.appendChild(a);
      a.click();
    },

    // 添加活动按钮
    handleAdd() {
      // this.$router.push({name:'activityGoodsAdd',query:{}})
      this.dialogVisible = true;
    },
    // 填写线下核销码验证
    changeOffline(){
      if(this.offline_num*1>5000){
        this.offline_num = ''
        this.$message.warning('单次最多生成5000份')
      }
    },
    // 填写线上核销码验证
    changeOnline(){
      if(this.online_num*1>5000){
        this.online_num = ''
        this.$message.warning('单次最多生成5000份')
      }
    },
    // 添加弹出框确定
    addWriteOff() {
      this.creatLoad = true;
      this.creatText = '生成中'
      this.creatBtn = true
      let params = {
        prize_id: this.id,
        offline_num: this.offline_num ? this.offline_num : 0,
        online_num: this.online_num ? this.online_num : 0,
        market_id: this.marketId,
      };
      this.$http
        .post("/api/root/activity/prizecode/created", params)
        .then((res) => {
          console.log(res, "生成核销码结果");
          if (res.code == 1) {
            this.online_num = '';
            this.offline_num = '';
            this.$message.success("生成成功");
            this.dialogVisible = false;
            this.getSetList();
            this.creatLoad = false;
            this.creatText = '确定'
            this.creatBtn = false
          } else {
            this.$message.warning(res.msg);
            this.creatLoad = false;
            this.creatText = '确定'
            this.creatBtn = false
          }
        });
    },

    // 删除按钮
    toDel(id) {
      this.$confirm("此操作将删除该核销码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http
          .post("/api/root/activity/prizecode/del", { id })
          .then((res) => {
            console.log(res);
            if (res.code == 1) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getSetList();
            } else {
              this.$message.warning(res.msg);
            }
          });
      });
    },

    // 编辑按钮
    toEdit(id) {
      this.$router.push({ name: "activityGoodsAdd", query: { id } });
    },

    // 更改状态
    toChange(id, sta) {
      let params = {
        id,
        status: sta == 1 ? 0 : 1,
      };
      this.$http.post("/api/root/activity/son/status", params).then((res) => {
        console.log(res, "更改状态");
        if (res.code == 1) {
          this.$message.success("更改成功");
          this.getSetList();
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // 关闭对话框
    closedFn() {
      this.offline_num = "";
      this.online_num = "";
      this.addMarketId = "";
    },

    // 多选
    handlerCheckbox(i) {
      console.log(i);
      let arr = this.checkBoxAll;
      if (arr.includes(i)) {
        let index = arr.indexOf(i);
        if (index != -1) {
          arr.splice(index, 1);
          this.shelvesAlls.splice(index, 1);
          if (this.checkBoxAll.length !== this.tableList.length) {
            this.checkAll = false;
          }
        }
      } else {
        this.checkBoxAll.push(i);
        this.shelvesAlls.push(this.tableList[i].code);
        if (this.checkBoxAll.length == this.tableList.length) {
          this.checkAll = true;
        }
      }
      console.log(this.shelvesAlls);
    },
    // 全选与全不选
    handerCheckAll() {
      this.checkAll = !this.checkAll;
      let arr = this.tableList.length;
      this.checkBoxAll = [];
      this.shelvesAlls = [];
      if (this.checkAll) {
        for (let i = 0; i < arr; i++) {
          this.checkBoxAll.push(i);
        }
        this.checkBoxAll.map((v) => {
          this.shelvesAlls.push(this.tableList[v].code.toString());
        });
      } else {
        this.checkBoxAll = [];
        this.shelvesAlls = [];
      }
      console.log(this.shelvesAlls);
    },

    //更改直播配置
    // toChange(id,sta){
    //     let status = sta==0?1:0;
    //     this.$http.post('/api/root/SystemConfig/changeStatus',{id,status}).then(res=>{
    //         console.log(res,'直播配置结果');
    //         if(res.code==1){
    //             this.$message.success('操作成功')
    //             this.getSetList()
    //         }else{
    //             this.$message.warning(res.msg)
    //         }
    //     })
    // },

    handleSizeChange(val) {
      this.page = 1
      this.pageSize = val;
      this.getSetList();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getSetList();
    },
  },
};
</script>
<style lang="less">
@import "index.less";
</style>